/**
 * 工具类
 */
import store from '@/store'
import pako from "@/utils/pako.min.js"
import config from "@/config.js"

/**
 * 格式化日期格式 (用于兼容ios Date对象)
 */
export const formatDate = (time) => {
	// 将xxxx-xx-xx的时间格式，转换为 xxxx/xx/xx的格式 
	return time.replace(/\-/g, "/");
}

/**
 * 对象转URL
 * @param {object} obj
 */
export const urlEncode = (obj = {}) => {
	const result = []
	for (const key in obj) {
		const item = obj[key]
		if (!item) {
			continue
		}
		if (isArray(item)) {
			item.forEach(val => {
				result.push(key + '=' + val)
			})
		} else {
			result.push(key + '=' + item)
		}
	}
	return result.join('&')
}

/**
 * 遍历对象
 */
export const objForEach = (obj, callback) => {
	Object.keys(obj).forEach((key) => {
		callback(obj[key], key)
	});
}

/**
 * 是否在数组内
 */
export const inArray = (search, array) => {
	for (var i in array) {
		if (array[i] == search) return true
	}
	return false
}

/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(Y)、月(m)、日(d)、小时(H)、分(M)、秒(S) 可以用 1-2 个占位符，
 * 例子：
 * dateFormat('YYYY-mm-dd HH:MM:SS', new Date()) ==> 2020-01-01 08:00:00
 */
export const dateFormat = (fmt, date) => {
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"m+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"M+": date.getMinutes().toString(), // 分
		"S+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	let ret
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt)
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt
}
// val 时间戳
export const formatDayTime = (val) => {
	if (val) {
		let date = new Date(val)
		let Y = date.getFullYear();
		let M = date.getMonth() + 1;
		let D = date.getDate();

		if (M < 10) {
			M = '0' + M;
		}
		if (D < 10) {
			D = '0' + D;
		}

		return Y + '-' + M + '-' + D;
	} else {
		return '';
	}
};

/**
 * 判断是否为空对象
 * @param {*} object 源对象
 */
export const isEmptyObject = (object) => {
	return Object.keys(object).length === 0
}

/**
 * 判断是否为对象
 * @param {*} object
 */
export const isObject = (object) => {
	return Object.prototype.toString.call(object) === '[object Object]'
}

/**
 * 判断是否为数组
 * @param {*} array
 */
export const isArray = (array) => {
	return Object.prototype.toString.call(array) === '[object Array]'
}

/**
 * 判断是否为空
 * @param {*} object 源对象
 */
export const isEmpty = (value) => {
	if (isArray(value)) {
		return value.length === 0
	}
	if (isObject(value)) {
		return isEmptyObject(value)
	}
	return !value
}

/**
 * 对象深拷贝
 * @param {*} obj 源对象
 */
export const cloneObj = (obj) => {
	let newObj = obj.constructor === Array ? [] : {};
	if (typeof obj !== 'object') {
		return;
	}
	for (let i in obj) {
		newObj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
	}
	return newObj
}

// 节流函数
// 思路： 第一次先设定一个变量true，
// 第二次执行这个函数时，会判断变量是否true，
// 是则返回。当第一次的定时器执行完函数最后会设定变量为flase。
// 那么下次判断变量时则为flase，函数会依次运行。
export function throttle(fn, delay = 100) {
	// 首先设定一个变量，在没有执行我们的定时器时为null
	var timer = null
	return function () {
		// 当我们发现这个定时器存在时，则表示定时器已经在运行中，需要返回
		if (timer) return
		timer = setTimeout(() => {
			fn.apply(this, arguments)
			timer = null
		}, delay)
	}
}

// 防抖函数
// 首次运行时把定时器赋值给一个变量， 第二次执行时，
// 如果间隔没超过定时器设定的时间则会清除掉定时器，
// 重新设定定时器， 依次反复， 当我们停止下来时，
// 没有执行清除定时器， 超过一定时间后触发回调函数。
// 参考文档：https://segmentfault.com/q/1010000021145192
export function debounce(fn, delay) {
	let timer
	return function () {
		const that = this
		const _args = arguments // 存一下传入的参数
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(function () {
			fn.apply(that, _args)
		}, delay)
	}
}


/**
 * 数组交集
 * @param {Array} 数组1
 * @param {Array} 数组2
 * @return {Array}
 */
export const arrayIntersect = (array1, array2) => {
	return array1.filter(val => array2.indexOf(val) > -1)
}
// 测评持续增长人数
export const getImitateHot = (initial, multiple) => {
	let initTime = '2018/01/01 00:00:00';
	let num = new Date(initTime).getTime();
	let time = new Date().getTime();
	let t = time - num;
	let d = Math.floor(t / 1000 / 60 / 60 / 24);
	let hours = d * 24 + parseInt(((time - num) % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	return parseInt(initial + parseInt(hours / multiple) * 1000);
}

//判断是否登录
export const checkLogin = () => {
	const userInfo = uni.getStorageSync('userInfo');
	return !!userInfo
}
//判断是否VIP
export const isVIP = () => {
	const userInfo = uni.getStorageSync('userInfo');
	return userInfo && userInfo.userPermissionId >= 3
}

export const computesNavHeight = () => {
	const navHeightObj = {};
	const res = uni.getSystemInfoSync();
	if (res && res['system']) {
		navHeightObj.navigationCustomStatusHeight = res.statusBarHeight;
		if (res['system'].indexOf('Android') != -1) {

			navHeightObj.system = 'android';
			navHeightObj.navigationCustomCapsuleHeight = 48
		} else {
			navHeightObj.system = 'ios'
			navHeightObj.navigationCustomCapsuleHeight = 44
		}
		navHeightObj.height = navHeightObj.navigationCustomStatusHeight + navHeightObj.navigationCustomCapsuleHeight
	}
	return navHeightObj
}
/**
 * 字体解码 
 * @param {String} 省份解码文字
 */
export const fontDecode = (str) => {
	var l = str.length / 5;
	var b = "";
	for (let i = 0; i < l; i++) {
		b += String.fromCharCode(parseInt(str.substr(i * 5, 5)));
	}
	var w = "";
	b.split("|").forEach(function (v, i) {
		if (i > 0) {
			if (String(v).length == 1) {
				w += v;
			} else {
				w += "&#x" + v + ";";
			}
		}
	});
	return w;
}

// 服务器时间格式化
export const transDateTime = (time, format) => {
	var transTime = '';
	transTime = new Date(time);
	transTime = dateFormat(format ? format : 'YYYY-mm-dd HH:MM', transTime);
	return transTime;
}
// 服务器时间格式化无年份
export const transDateTimeNoYear = (time, format) => {
	var transTime = '';
	transTime = new Date(time);
	transTime = dateFormat(format ? format : 'mm-dd HH:MM', transTime);
	return transTime;
}
/**
 * 格式化时间格式
 * @param { string | number } time 服务器时间
 * @param { string | number } module [live/news] 功能模块(不同模块时间格式不同) 
 * @return { string } 
 */
export const getDateDiff = (time, module = 'news') => {
	// 当前时间
	var nowTime = new Date();
	var year = nowTime.getFullYear();
	var month = nowTime.getMonth() + 1;
	var day = nowTime.getDate();
	var hours = parseInt(nowTime.getHours());
	var minutes = nowTime.getMinutes();
	time = time.replace('T', ' ')
	// 传来time 2018-05-25 18:14:02 分解
	var timeyear = time.substring(0, 4);
	var timemonth = time.substring(5, 7);
	var timeday = time.substring(8, 10);
	var timehours = parseInt(time.substring(11, 13));
	var timeminutes = time.substring(14, 16);
	var targetTime = new Date()
	targetTime.setFullYear(parseInt(timeyear), parseInt(timemonth) - 1, parseInt(timeday))
	targetTime.setHours(parseInt(timehours), parseInt(timeminutes))
	var d_year = year - timeyear;
	var d_month = Math.abs(month - timemonth);
	var d_day = Math.abs(day - timeday);
	var d_hours = hours - timehours;
	var d_minutes = minutes - timeminutes;
	if (module == 'news') {
		if (d_year >= 1) {
			return timeyear + '-' + timemonth + '-' + timeday
		} else {
			if (d_month >= 1) {
				return timemonth + '-' + timeday
			} else {
				if (d_day <= 1) {
					switch (d_day) {
					case 0:
						if (d_hours == 0) {
							if (d_minutes > 0) {
								return d_minutes + '分钟前';
							} else return '刚刚';
						} else if (d_hours ==1) {
							if (d_minutes >= 0) {
								return d_hours + '小时前'
							} else {
								return (60 + d_minutes) + '分钟前';
							}
						} else {
							return d_hours + '小时前';
						}
						break;
					case 1:
						if (d_hours < 0) {
							return 24 + d_hours + '小时前';
						} else {
							return d_day + '天前';
						}
						break;
					}
				} else {
					if (d_day < 7) {
						return d_day + '天前';
					} else {
						return timemonth + '-' + timeday
					}
				}
			}
		}
	} else if (module == 'live') {
		if (d_year >= 1) {
			return timeyear + '-' + timemonth + '-' + timeday + ' ' + timehours + ':' + timeminutes
		} else {
			return timemonth + '-' + timeday + ' ' + timehours + ':' + timeminutes
		}
	}
}
/**
 * 计算两个日期之前的相隔天数
 * @param {startDateStr} str 2023-01-01
 * @param {endDateStr} str 2023-01-03
 * @returns number 2
 */
export const dateDiffStr = (startDateStr, endDateStr) => {
	var day = 0;
	var separator = "-"; //日期分隔符
	var date1 = startDateStr.substring(0, 10).split(separator);
	var date2 = endDateStr.substring(0, 10).split(separator);
	var date11 = new Date(date1[0], date1[1] - 1, date1[2]);
	var date22 = new Date(date2[0], date2[1] - 1, date2[2]);
	day = parseInt(Math.abs(date22 - date11) / (1000 * 60 * 60 * 24));
	return day;
}



//下载文件打开PDF
export function openPdf(filePath, type, name) {
	// #ifdef MP-DINGTALK
	dd.saveFileToDingTalk({
		url: filePath, // 文件在第三方服务器地址
		name: name + '.pdf',
		success: (res) => {
			if (!res.data.length) return;
			dd.previewFileInDingTalk({
				spaceId: res.data[0].spaceId,
				fileId: res.data[0].fileId,
				fileName: '报告',
				fileSize: res.data[0].fileSize,
				fileType: "pdf",
			})
		},
		fail: (err) => {}
	})
	// #endif

	// #ifndef MP-DINGTALK
	uni.downloadFile({
		url: filePath,
		success: function (res) {
			const filePath = res.tempFilePath;
			uni.openDocument({
				filePath: filePath,
				success: function (res) {
					//判断是否是新的测评，如果是打开PDF以后返回上一页
					if (type == 'ceping' && type) {
						uni.navigateBack();
					}
				}
			});
		}
	});
	// #endif

}


// 校验手机号是否合规
export const checkPhone = (phone) => {
	let reg = /^1([3|4|5|6|7|8|9])\d{9}$/;
	if (reg.test(phone)) {
		return true;
	} else {
		return false;
	}
}


/** 阅读数量格式单位
 *  @param { string | number } count 接口返回的阅读次数
 */
export const readCount = (count) => {
	count = Number(count)
	if (count > 9999) {
		return (count / 10000).toFixed(1) + '万'
	} else {
		return count
	}
}



// 原生实现window.atob,用于解码使用 base64 编码的字符串
export const atob = (string) => {
	let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	let b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
	string = String(string).replace(/[\t\n\f\r ]+/g, "");
	if (!b64re.test(string))
		throw new TypeError(
			"Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
	string += "==".slice(2 - (string.length & 3));
	let bitmap, result = "",
		r1, r2, i = 0;
	for (; i < string.length;) {
		bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12 |
			(r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));
		result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) :
			r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) :
			String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
	}
	return result;
}
// 解压数据
export const unzip = (gizp) => {
	const gzipData = new Uint8Array(
		atob(gizp)
		.split('')
		.map((char) => char.charCodeAt(0))
	)
	const unzipData = pako.inflate(gzipData, {
		to: 'string'
	})
	return JSON.parse(unzipData)
}
export const getMainColor = () => {
	return {
		ToB: `#${store.state.storesInfo?.color}`,
		ToC: "#6665EB",
		ToG: "#2678e3"
	} [config.origin]
}
// 电话号码脱敏
export function phoneCode(tel) {
	if (!tel) return tel;
	// replace() 方法用于在字符串中用一些字符替换另一些字符，或替换一个与正则表达式匹配的子串。
	const phone = tel.replace(tel.substring(3, 7), '****')
	return phone
}
/**
 * 上传图片
 * @param { array } uploadList 上传的临时文件地址
 * @param { string } Module [news/useravatar/feedback...] 自定义命名
 * @param { boolean } IsWatermark 是否生成水印图
 * @return { array } 
 */
export const uploadImg = (uploadList, Module, IsWatermark = false) => {
	return new Promise((resolve, reject) => {
		let uploadResult = [],
			count = 0;
		// AppId 应用标识 优志愿=1 优家=2 (优生涯、优艺考、高招云、优测评等归属于1)
		// PlatForm 平台来源（比如 android/ios/pc/h5/admin/mp）
		let url = config.apiUrl +
			`youzy.util4y.common.photo.upload?AppId=1&PlatForm=mp_ucp&Module=${Module}&IsWatermark=${IsWatermark}`
		uploadList.map((item, index) => {
			uni.uploadFile({
				filePath: item,
				name: "file",
				url,
				success: res => {
					uploadResult.push(JSON.parse(res.data).result)
					if (count == uploadList.length - 1) {
						resolve(uploadResult)
					}
					++count
				},
				fail(err) {
					reject(err)
				},
			});
		})
	})
}

/** 生成随机字符串
 * @param { Number } length 字符串长度
 * @param { String } chars 字符集
 */
export function generateRandomString(length = 32, chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    let result = '';
    for (let i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
}

//字符串进行解密   
export const uncompileStr = (code) => {
	code = unescape(code);
	var c = String.fromCharCode(code.charCodeAt(0) - code.length);
	for (var i = 1; i < code.length; i++) {
		c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
	}
	return c;
}
